use askama_axum::{IntoResponse, Template};
use axum::{extract::{Path, Query, State}, response::{Html, Redirect}, Form};
use tower_cookies::Cookies;
use tower_sessions::Session;
use crate::{core::xerror::{XErrors, GLOBALERROR}, services::backend::category_service::CategoryService, types::backend::blog_type::BlogListReq};
use crate::core::AppState;
use crate::types::common::Breadcrumb;
use crate::services::backend::blog_service::BlogService;
use crate::types::backend::blog_type::{BlogForm, BlogRow};
use crate::types::common::OptionRow;
use super::{AdminSession, ErrorTemplate};

#[derive(Template)]
#[template(path = "backend/blog/list.html")]
struct BlogListTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    paginate: String,
    list: Vec<BlogRow>,
    categorys: Vec<OptionRow>
}


#[derive(Template)]
#[template(path = "backend/blog/form.html")]
struct BlogFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: BlogForm,
    url: String, // action url 
    categorys: Vec<OptionRow>
}


/// 获取文章分页
pub async fn blogs_handler(State(state): State<AppState>, session: Session, Query(args):Query<BlogListReq>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    // 获取所有分类
    let categorys_res = CategoryService::get_option_categorys(&state.db).await;
    let categorys = match categorys_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };

    let res = BlogService::get_blog_page(&state.db, &args).await;
    let breadcrumb = Breadcrumb {
        title: "文章管理".to_string(),
        sub_title: "文章列表".to_string(),
    };
   
    match res {
        Ok(data) => {
            let template = BlogListTemplate {
                auth,
                breadcrumb,
                paginate: data.paginate, 
                list: data.list,
                categorys
            };
            Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate {
                msg: e.to_string()
            };
            Html(template.render().unwrap())
        }
    }
   
}

/// 添加文章表单
pub async fn add_blog_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let breadcrumb = Breadcrumb {
        title: "文章管理".to_string(),
        sub_title: "添加文章".to_string(),
    };
    // 获取所有分类
    let categorys_res = CategoryService::get_option_categorys(&state.db).await;
    let categorys = match categorys_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };
    
    let template = BlogFormTemplate {
        auth,
        breadcrumb,
        data: BlogForm{
            cid: 0,
            title: "".to_string(), 
            seo_title: "".to_string(), 
            seo_keywords: "".to_string(), 
            seo_description: "".to_string(), 
            description: "".to_string(), 
            image: "".to_string(),
            is_show: 0,
            is_top: 0,
            hits: 0,
            content: "".to_string(),
        },
        url: "/backend/blog/create".to_string(),
        categorys
    };
    return Html(template.render().unwrap());
}


/// 添加文章操作
pub async fn create_blog_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Form(form): Form<BlogForm>) -> Redirect {
    let error = XErrors::new();
    if form.title.is_empty() || form.cid == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/blog/create");
    }
    let res = BlogService::insert_blog(&state.db, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, "".to_string());
            return Redirect::to("/backend/blog/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, db_error);
            return Redirect::to("/backend/blog/list");
        }
    }
}

/// 修改文章表单
pub async fn edit_blog_handler(State(state): State<AppState>, session: Session, Path(id): Path<i64>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    // 获取所有分类
    let categorys_res = CategoryService::get_option_categorys(&state.db).await;
    let categorys = match categorys_res {
        Ok(data) => data,
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    };

    let res = BlogService::get_blog_by_id(&state.db, id).await;
    let breadcrumb = Breadcrumb {
        title: "文章管理".to_string(),
        sub_title: "修改文章".to_string(),
    };
    match res {
        Ok(data) => {
            let template = BlogFormTemplate {
                auth,
                breadcrumb,
                data,
                url: format!("/backend/blog/edit/{}", id),  
                categorys 
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
}

/// 修改文章操作
pub async fn update_blog_handler(
    State(state): State<AppState>, 
    cookies: Cookies, 
    Path(id): Path<i64>,
    Form(form): Form<BlogForm>) -> Redirect {
    let error = XErrors::new();
    // 名称不能为空
    if form.title.is_empty() || form.cid == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to(format!("/backend/blog/edit/{}", id).as_str());
    }

    let res = BlogService::update_blog(&state.db, id, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/blog/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/blog/list");
        }
    }
}

/// 删除文章操作
pub async fn delete_blog_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>) -> Redirect {
    let error = XErrors::new();
    // 是否存在
    let exist = BlogService::exist_blog_by_id(&state.db, id).await;
    let total = match exist {
        Ok(total) => total,
        Err(_) => 0,
    };
    if total == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::RECORDNOTFOUND, "".to_string());
        return Redirect::to("/backend/blog/list");
    }
    let res = BlogService::delete_blog(&state.db, id).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::DELETESUCCESS, "".to_string());
            return Redirect::to("/backend/blog/list");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::DELETEFAILED, db_error);
            return Redirect::to("/backend/blog/list");
        }
    }
}